# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     interface_cases.py
    Description:   测试接口用例视图
 -------------------------------------------------
 """
from typing import Type

# from ApiTestEngine.core.cases import run_test
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from apps.test_projects.models import TestEnv
# from apps.api_tests.serializers import InterFaceSerializer
# Create your views here.

from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet
from utils.json_response import ErrorResponse, SuccessResponse
from apps.api_tests import models


class InterFaceCaseSerializer(CustomModelSerializer):
    """
    接口用例管理-序列化器
    """

    class Meta:
        model = models.InterFaceCase
        fields = '__all__'


class InterFaceCaseListSerializer(CustomModelSerializer):
    """
    接口用例 列表-序列化器
    """

    class Meta:
        model = models.InterFaceCase
        fields = (
            'id',
            'title'
        )


class InterFaceCaseDetailSerializer(CustomModelSerializer):
    """
    接口用例 详情-序列化器
    """
    from apps.api_tests.views.interface import InterFaceSerializer
    # 嵌套序列化器: 关联接口信息
    interface = InterFaceSerializer()

    class Meta:
        model = models.InterFaceCase
        fields = '__all__'


class InterFaceCaseViewSet(CustomModelViewSet):
    """
    接口用例管理-视图
    """
    queryset = models.InterFaceCase.objects.all()
    serializer_class = InterFaceCaseSerializer  # get_serializer自动获取这里的序列化器
    # 列表序列化器
    list_serializer_class = InterFaceCaseListSerializer
    retrieve_serializer_class = InterFaceCaseDetailSerializer

    permission_classes = [permissions.IsAuthenticated]
    # 设置查询过滤字段
    filterset_fields = ['interface']  # scene

    @action(methods=['POST'], url_path='run', detail=False, permission_classes=[IsAuthenticated])
    def run_cases(self, request):
        """
        :param request:
            env:测试环境
            cases_data:测试数据
        :return:
        """
        env_id = request.data.get('env')
        case_data = request.data.get('cases')

        if not all([env_id, case_data]):
            return ErrorResponse(msg="参数env和cases均不能为空")
        # 获取测试环境对象
        env = TestEnv.objects.get(id=env_id)
        # 获取用例运行的相关配置
        config = {
            "ENV": {
                'host': env.host,
                'headers': env.header,
                **env.global_var,
                **env.debug_global_variable
            },
            "DB": env.db,
            "global_func": env.global_func,
        }
        # res, debug_var = run_test(case_data=[{"Cases": [case_data]}], env_config=config, debug=True)
        # # 获取用例执行的结果
        # result = res['results'][0]['cases'][0]
        # # 保存debug模式的环境变量
        # env.debug_global_variable = debug_var
        # env.save()
        return SuccessResponse(data={
            "case_data": [{"Cases": [case_data]}],
            "env_config": config,
            'debug': True
        })
